package com.safe.text;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.safe.text.R;
import com.markupartist.android.widget.ActionBar.Action;
import com.parse.FindCallback;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.RequestPasswordResetCallback;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public abstract class BaseActivity extends Activity {

	boolean started = false;
	static double mph = 0.0;
	static double kph = 0.0;
	static String phoneNumber = "";
	static String emailAddress = "";
	static String password = "";
	static Context currentActivity = null;
	static String UserId = "";
	static boolean registered = true;
	static boolean parseIsRunning = false;
	boolean loggedIn = false;
	static String KEY_FIRST_RUN = "installDate";
	static String KEY_START_ON_BOOT = "startOnBootup";
	static String KEY_SMS_PREF = "smsPref";
	StoredData db = new StoredData(this);
	ProgressDialog progress;


		public boolean onCreateOptionsMenu(Menu menu) {
		    MenuInflater inflater=getMenuInflater();
		    inflater.inflate(R.menu.menu, menu);
		    return super.onCreateOptionsMenu(menu);

		}
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
		    switch(item.getItemId())
		    {
		    case R.id.logout:
		    	LougOut();
		        break;
		    }
		    return true;
		}

	
		public void LougOut() {
	    	Parse.initialize(this, "tbLiAmAO28YdbVjTaNGJOCHyJgKvRanwIM2pzhQH",
					"jummwB87UtOWbPhhAjiAFoYgHLDB2P92JyuzYrEe");
			ParseUser.logOut();
			final SharedPreferences prefs = PreferenceManager
			.getDefaultSharedPreferences(currentActivity);
			prefs.edit().clear();
			prefs.edit().commit();
	    	db.open();
	    	db.deleteAllUsers();
	    	db.deleteAllSMS();
	    	finish();
	    	db.close();
		}
	
	
	
	public void populateTable() {
		// get the tableLayout which we created in main.xml
		TableLayout tl = (TableLayout) findViewById(R.id.smsHistoryTable);
		// Create a new row to be added.
		TableRow tr2 = new TableRow(this);

		tl.removeAllViews();

		// Add Headers
		createHeader(tr2, new TextView(this), "Date Sent");
		createHeader(tr2, new TextView(this), "Time Sent");
		createHeader(tr2, new TextView(this), "MPH");
		createHeader(tr2, new TextView(this), "KPH");
		tl.addView(tr2);

		// Populate rows
		db.open();
		Cursor c2 = db.getAllSMS();
		while (c2.moveToNext()) {
			// Create a new row to be added.
			TableRow tr = new TableRow(this);
			// Create text views to be added to the row.
			TextView tv1 = new TextView(this);
			TextView tv2 = new TextView(this);
			TextView tv3 = new TextView(this);
			TextView tv4 = new TextView(this);
			// Put the data into the text view by passing it to a user defined
			// function createView()
			createView(tr, tv1, c2.getString(1));
			createView(tr, tv2, c2.getString(2));
			createView(tr, tv3, c2.getString(3));
			createView(tr, tv4, c2.getString(4));
			// Add the new row to our tableLayout tl
			tl.addView(tr);
		}
		db.close();
	}

	public void createView(TableRow tr, TextView t, String viewdata) {
		t.setText(viewdata);
		// adjust the porperties of the textView
		t.setTextColor(Color.parseColor("#F1E9F7"));
		t.setBackgroundColor(Color.parseColor("#5E0DAC"));
		t.setPadding(25, 0, 0, 0);
		t.setGravity(Gravity.CENTER);
		t.setInputType(InputType.TYPE_CLASS_TEXT
				| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		tr.setPadding(0, 1, 0, 1);
		tr.setBackgroundColor(Color.parseColor("#8D41D6"));
		tr.addView(t); // add TextView to row.
	}

	public void createHeader(TableRow tr, TextView t, String viewdata) {
		t.setText(viewdata);
		// adjust the porperties of the textView
		t.setTextColor(Color.parseColor("#F1E9F7"));
		t.setTypeface(null, Typeface.BOLD);
		t.setPadding(25, 0, 0, 0);
		t.setGravity(Gravity.CENTER);
		tr.setPadding(0, 1, 0, 1);
		tr.setBackgroundColor(Color.parseColor("#3B0470"));
		tr.addView(t); // add TextView to row.
	}

	public boolean isLoggedIn() {
		Parse.initialize(this, "tbLiAmAO28YdbVjTaNGJOCHyJgKvRanwIM2pzhQH",
				"jummwB87UtOWbPhhAjiAFoYgHLDB2P92JyuzYrEe");
		ParseUser currentUser = ParseUser.getCurrentUser();
		if (currentUser != null) {
			Log.e("isloggedin", "true");
			return true;
		} else {
			Log.e("isloggedin", "false");
			return false;
		}
	}

	public void updateParseUsersTable(final String functionId,
			final String email, final String newEmail, final String pass,
			final String newPass,  final String phone,
			final boolean isAppOn, final boolean runAtStartup,
			final boolean prefSMS) {
		Parse.initialize(this, "tbLiAmAO28YdbVjTaNGJOCHyJgKvRanwIM2pzhQH",
				"jummwB87UtOWbPhhAjiAFoYgHLDB2P92JyuzYrEe");
		final SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(currentActivity);
		final SharedPreferences.Editor prefsEditor = prefs.edit();
		//Log.e("email/pass", email + "/" + pass);
		ParseUser user = ParseUser.getCurrentUser();
		if (user != null) {
			//Log.d("Login", "Your login was successful");
			if (functionId == "ParseEmailUpdate") {
				user.setEmail(newEmail);
				user.setUsername(newEmail);
				BaseActivity.emailAddress = newEmail;
				prefsEditor.putString("emailAddress", newEmail);
				prefsEditor.commit();
				makeToast("Your email address was successfully updated");
			}
			if (functionId == "ParsePasswordUpdate") {
				user.setPassword(newPass);
				BaseActivity.password = newPass;
				prefsEditor.putString("password", newPass);
				prefsEditor.commit();
				makeToast("Your password was successfully updated");
			}
			if (functionId == "ParsePhoneUpdate") {
				user.put("PhoneNumber", phone);
				BaseActivity.phoneNumber = phone;
				prefsEditor.putString("PhoneNumber", phone);
				prefsEditor.commit();
				makeToast("Your phone number was successfully updated");
			}
			if (functionId == "ParseAppOn") {
				user.put("isAppOn", isAppOn);
			}
			if (functionId == "ParseSMSPref") {
				user.put("smsPref", prefSMS);
			}
			if (functionId == "ParseAppStart") {
				user.put("runAtStartup", runAtStartup);
			}
			user.saveInBackground();
		} else {
			Log.d("Login", "Your login failed: ");
			makeToast("There was an issue saving your changes, please check your internet connection and try again.");
		}
		parseIsRunning = false;
	}

	public void sendResetPasswordEmail(final String email) {
		ParseUser.requestPasswordResetInBackground(email,
				new RequestPasswordResetCallback() {
					public void done(ParseException e) {
						if (e == null) {
							makeToast("An email has been sent to "
									+ email
									+ " with instructions to reset your password.");
						} else {
							makeToast("The following error has occued, please verify that you entered the correct email address: "
									+ e);
						}
					}
				});
	}

	// The definition of our task class
	   class getDrivingHist extends AsyncTask<Integer, Integer, String> {

	  
	  protected void onPreExecute() {
	     super.onPreExecute();
			progress = new ProgressDialog(currentActivity);
			progress.setMessage("Getting Driving History...");
			progress.show();
	    // displayProgressBar("Downloading...");
	  }

	  protected String doInBackground(Integer... params) {
			
		  try {
				final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(currentActivity);
			  if (UserId==""){
				  getUserObjectId(prefs.getString("emailAddress", ""), prefs.getString("password", ""));
				  Thread.sleep(1000);
			  }
			Parse.initialize(currentActivity,
						"tbLiAmAO28YdbVjTaNGJOCHyJgKvRanwIM2pzhQH",
						"jummwB87UtOWbPhhAjiAFoYgHLDB2P92JyuzYrEe");
				ParseQuery query = new ParseQuery("DrivingHistory");

				query.whereEqualTo("UserId", UserId);
				final StoredData db = new StoredData(currentActivity);
				

				query.findInBackground(new FindCallback() {
					public void done(List<ParseObject> historyList, ParseException e) {
						if (e == null) {
							int count;
								count = historyList.size();
								db.open();
								db.deleteAllSMS();
								db.close();
							for (int i = 0; i < count; i++) {
								db.open();
								db.insertSms(historyList.get(i)
										.getString("SMSSentDate"), historyList.get(i)
										.getString("SMSSentTime"), historyList.get(i)
										.getString("averagemph"), historyList.get(i)
										.getString("averagekph"));
								// change averagemph to mps
								db.close();
							}

							Log.d("historyList", "Retrieved " + historyList.size()
									+ " SMS records");
						} else {
							Log.d("historyList", "Error: " + e.getMessage());
							
						}
					}

				});
				Thread.sleep(1000);
				return "Finish";

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "Error";
		}
		  
	  }

	  @Override
	  protected void onProgressUpdate(Integer... values) {
	     super.onProgressUpdate(values);
	    // updateProgressBar(values[0]);
	  }

	  @Override
	  protected void onPostExecute(String result) {
	     super.onPostExecute(result);
	     if (result == "Finish"){
	    	 Log.e("DHFIN", "DHFIN");
				progress.cancel();
				finish();
				Intent intent = new Intent(currentActivity,
						MainActivity.class);
				startActivity(intent);
	     }
	     if (result == "Error") {
	    	 progress.cancel();
	    	 Log.e("DHFerr", "DHFerror");
	    	 makeToast("Error has occured");
	     }
	  //   dismissProgressBar();
	  }

	  }

	public static void getUserObjectId(String email, String pass) {
		Parse.initialize(currentActivity,
				"tbLiAmAO28YdbVjTaNGJOCHyJgKvRanwIM2pzhQH",
				"jummwB87UtOWbPhhAjiAFoYgHLDB2P92JyuzYrEe");
		ParseUser user = ParseUser.getCurrentUser();
		if (user != null) {
			Log.d("Login", "Your login was successful");
			UserId = user.getObjectId();
		} else {
			Log.d("Login", "Your login failed");
			UserId = "";
		}

	}

	public void isEmailAlreadyRegistered(String email, String pass) {
		Parse.initialize(currentActivity,
				"tbLiAmAO28YdbVjTaNGJOCHyJgKvRanwIM2pzhQH",
				"jummwB87UtOWbPhhAjiAFoYgHLDB2P92JyuzYrEe");
		ParseUser.logInInBackground(email, pass, new LogInCallback() {
			public void done(ParseUser user, ParseException e) {
				if (user != null) {
					Log.d("Login", "Your login was successful");
					UserId = user.getObjectId();
					registered = true;
				} else {
					Log.d("Login", "Your login failed: " + e);
					registered = false;
				}
			}
		});

	}

	public void UserLogin(final String email, final String pass) {
		Parse.initialize(this, "tbLiAmAO28YdbVjTaNGJOCHyJgKvRanwIM2pzhQH",
				"jummwB87UtOWbPhhAjiAFoYgHLDB2P92JyuzYrEe");
		ParseUser.logInInBackground(email, pass, new LogInCallback() {
			public void done(ParseUser user, ParseException e) {
				if (user != null) {
					Log.d("Login", "Your login was successful");
					loggedIn = true;
					Log.d("login", loggedIn + "");
					final SharedPreferences prefs = PreferenceManager
							.getDefaultSharedPreferences(currentActivity);
					final SharedPreferences.Editor prefsEditor = prefs.edit();
					prefsEditor.putString("emailAddress", email);
					prefsEditor.putString("password", pass);
					prefsEditor.putString("phoneNumber",
							user.getString("PhoneNumber"));
					phoneNumber = user.getString("PhoneNumber");
					emailAddress = user.getString("email");
					password = user.getString("password");
					UserId = user.getObjectId();
					prefsEditor.putBoolean(KEY_START_ON_BOOT,
							user.getBoolean("runAtStartup"));
					prefsEditor.putBoolean(KEY_SMS_PREF,
							user.getBoolean("smsPref"));
					prefsEditor.putBoolean("serviceStatus",
							user.getBoolean("isAppOn"));
					prefsEditor.commit();
					// Checks if New Install
					String installationDate = getDate(
							prefs.getLong(KEY_FIRST_RUN, 0),
							"MM/dd/yyyy h:mm aa");
					if (isNewInstall(user.getString("FirstInstallDate"),
							user.getString("MostRecentInstallDate"),
							installationDate)) {
						user.put("MostRecentInstallDate", installationDate);
						user.saveInBackground();
					}
					// Start the service if the service did not execute
					// onDestroy
					final Intent mainService = new Intent(currentActivity,
							MainService.class);
					if (prefs.getBoolean("serviceStatus", false)) {
						if (!isMyServiceRunning()) {
							startService(mainService);
						}
					}
					loggedIn = true;
				} else {
					Log.d("Login", "Your login failed: " + e);
					loggedIn = false;
				}
			}
		});
		parseIsRunning = false;
	}

	public boolean isNewInstall(String firstInstall, String secondInstall,
			String mostRecentInstall) {
		if (firstInstall == mostRecentInstall) {
			return false;
		} else if (secondInstall == mostRecentInstall) {
			return false;
		} else {
			return true;
		}
	}
	
	public void ParseAppStart(String email, String pass, boolean runAtStart) {
		updateParseUsersTable("ParseAppStart", email, "", pass, "", "", 
				false, runAtStart, false);
	}

	public void ParseSMSPref(String email, String pass, boolean prefSMS) {
		updateParseUsersTable("ParseSMSPref", email, "", pass, "", "",
				false, false, prefSMS);
	}

	public void ParseAppOn(String email, String pass, boolean isAppOn) {
		parseIsRunning = true;
		updateParseUsersTable("ParseAppOn", email, "", pass, "", "", 
				isAppOn, false, false);

	}

	public void ParseEmailUpdate(String email, String pass, String newEmail) {
		updateParseUsersTable("ParseEmailUpdate", email, newEmail, pass, "",
				"",  false, false, false);
	}

	public void ParsePasswordUpdate(String email, String pass, String newPass) {
		updateParseUsersTable("ParsePasswordUpdate", email, "", pass, newPass,
				"",  false, false, false);
	}

	public void ParsePhoneUpdate(String email, String pass, String phone) {
		updateParseUsersTable("ParsePhoneUpdate", email, "", pass, "", 
				phone, false, false, false);
	}

	public void LoginDialog(final Intent intent, final String activity) {
		final InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		AlertDialog.Builder alert = new AlertDialog.Builder(currentActivity);
		LinearLayout dialogLayout = new LinearLayout(currentActivity);
		alert.setMessage("You must enter your username and password to change the settings.");
		// Set an EditText view to get user input
		final EditText email2 = new EditText(currentActivity);
		final EditText password2 = new EditText(currentActivity);
		email2.setInputType(InputType.TYPE_CLASS_TEXT
				| InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
				| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		email2.setHint("Email Address");
		password2.setInputType(InputType.TYPE_CLASS_TEXT
				| InputType.TYPE_TEXT_VARIATION_PASSWORD
				| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		password2.setHint("Password");
		// Set an forgot password link
		final TextView forgotPassword = new TextView(currentActivity);
		forgotPassword.setPadding(10, 10, 0, 10);
		SpannableString content = new SpannableString("Forgot Password?");
		content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
		forgotPassword.setText(content);
		forgotPassword.setTextColor(Color.parseColor("#A069D6"));
		// configure dialogLayout
		dialogLayout.setOrientation(LinearLayout.VERTICAL);
		dialogLayout.addView(email2);
		dialogLayout.addView(password2);
		dialogLayout.addView(forgotPassword);
		alert.setView(dialogLayout);
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialoger, int whichButton) {
				String passwordInput = password2.getText().toString();
				String emailInput = email2.getText().toString();
				mgr.hideSoftInputFromWindow(email2.getWindowToken(), 0);
				mgr.hideSoftInputFromWindow(password2.getWindowToken(), 0);
				if (isPasswordFormatValid(password2.length()) && isEmailFormatValid(emailInput)) {
					final SharedPreferences prefs = PreferenceManager
							.getDefaultSharedPreferences(currentActivity);
					final SharedPreferences.Editor prefsEditor = prefs.edit();
					prefsEditor.putString("password", passwordInput);
					BaseActivity.password = passwordInput;
					prefsEditor.putString("emailAddress", emailInput);
					//Log.e("password", passwordInput);
					prefsEditor.commit();
					BaseActivity.emailAddress = emailInput;
					  parseIsRunning = true;
					  UserLogin(emailAddress, password);
					loginAsync hist = new loginAsync();
					hist.execute(activity, dialoger.toString());
					dialoger.cancel();
				}
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						mgr.hideSoftInputFromWindow(email2.getWindowToken(), 0);
						mgr.hideSoftInputFromWindow(password2.getWindowToken(),
								0);
						dialog.cancel();
					}
				});
		forgotPassword.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent settings = new Intent(currentActivity,
						SettingsActivity.class);
				// startActivity(settings);
				ForgotPasswordDialog();
				mgr.hideSoftInputFromWindow(email2.getWindowToken(), 0);
				mgr.hideSoftInputFromWindow(password2.getWindowToken(), 0);
			}

		});
		alert.show();
		email2.requestFocus();
		mgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	
	// The definition of our task class
	   class loginAsync extends AsyncTask<String, Integer, String> {

	  
	  protected void onPreExecute() {
	     super.onPreExecute();
			progress = new ProgressDialog(currentActivity);
			progress.setMessage("Logging In...");
			progress.show();
	    // displayProgressBar("Downloading...");
	  }

	  protected String doInBackground(String... params) {
			//Log.d("test", loggedIn + "");


			  
			  while(parseIsRunning){
				  try {
					  wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			  }
			  try {
				  Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (loggedIn) {
				//Log.e("t", "t3");
				if (params[0] == "Main") {
					return "DrivingHist";
				} else {
					return "Settings";
				}
			} else {

				return "Error";
			}

	  }

	  @Override
	  protected void onProgressUpdate(Integer... values) {
	     super.onProgressUpdate(values);
	    // updateProgressBar(values[0]);
	  }

	  @Override
	  protected void onPostExecute(String result) {
	     super.onPostExecute(result);
	     if (result == "Settings"){
Log.e("Settings", "Settings");
progress.cancel();
finish();
startActivity(new Intent(currentActivity,
		SettingsActivity.class));

	     } 
	     if (result == "Error"){
	    	 progress.cancel();
	    	 makeToast("The email address or password you entered is incorrect, please try again.");
	    	 Log.e("Finish", "Finish");
	     }
	     if (result == "DrivingHist"){
			//	getDrivingHist hist = new getDrivingHist();
			//	hist.execute(-1);
				
				progress.cancel();
				getDrivingHist hist = new getDrivingHist();
				hist.execute(-1);
				try {
					Thread.sleep(2500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				finish();
				Intent intent = new Intent(currentActivity,
						MainActivity.class);
				startActivity(intent);
				Log.e("DrivingHist", "DrivingHist");
	     }
	  //   dismissProgressBar();
	  }

	  }
	   
	   
	public void ForgotPasswordDialog() {
		final InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		AlertDialog.Builder alert = new AlertDialog.Builder(currentActivity);
		LinearLayout dialogLayout = new LinearLayout(currentActivity);
		alert.setMessage("Enter your email address to have the password reset link sent to you");
		// Set an EditText view to get user input
		final EditText email = new EditText(currentActivity);
		email.setInputType(InputType.TYPE_CLASS_TEXT
				| InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
				| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		email.setHint("Email Address");
		// configure dialogLayout
		dialogLayout.setOrientation(LinearLayout.VERTICAL);
		dialogLayout.addView(email);
		alert.setView(dialogLayout);
		alert.setPositiveButton("Send", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, int whichButton) {
				if (isEmailFormatValid(email.getText().toString())){
				sendResetPasswordEmail(email.getText().toString());
				mgr.hideSoftInputFromWindow(email.getWindowToken(), 0);
				}
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						mgr.hideSoftInputFromWindow(email.getWindowToken(), 0);
					}
				});

		alert.show();
		email.requestFocus();
		mgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}

	public void GPSAlert() {

		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(
				"GPS needs to be enabled in order to ensure accurate location updates. Would you like to enable the GPS locations now?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								startActivity(new Intent(
										Settings.ACTION_LOCATION_SOURCE_SETTINGS));
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(final DialogInterface dialog,
							final int id) {
						dialog.cancel();
					}
				});
		final AlertDialog alert = builder.create();
		alert.show();
		;

	}

	public void getHistoryAlert() {

		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(
				"Would you like to download the full driving history for this account?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								try {
									populateTable();
								} catch (Exception e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
								try {
									try {
										dialog.cancel();
										getDrivingHist hist = new getDrivingHist();
										hist.execute(-1);
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(final DialogInterface dialog,
							final int id) {
						dialog.cancel();
					}
				});
		final AlertDialog alert = builder.create();
		alert.show();
		;

	}

	public static String getDate(long milliSeconds, String dateFormat) {
		// Create a DateFormatter object for displaying date in specified
		// format.
		DateFormat formatter = new SimpleDateFormat(dateFormat);

		// Create a calendar object that will convert the date and time value in
		// milliseconds to date.
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(milliSeconds);
		return formatter.format(calendar.getTime());
	}

	public boolean isMyServiceRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (MainService.class.getName().equals(
					service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	// the home action
	class HomeAction implements Action {

		public int getDrawable() {
			return R.drawable.ic_action_name;
		}

		public void performAction(View view) {
			Intent home = new Intent(getApplicationContext(),
					MainActivity.class);
			if (currentActivity.getClass().getSimpleName()
					.equals("MainActivity")) {
			} else {
				if (currentActivity.getClass().getSimpleName()
						.equals("SettingsActivity")) {
					finish();
				}
				startActivity(home);
			}
		}

	}

	// the refresh action

	class RefreshAction implements Action {

		public int getDrawable() {
			return R.drawable.ic_action_refresh;
		}

		public void performAction(View view) {
			// if (currentActivity.getClass().getSimpleName()
			// .equals("MainActivity")) {
			getHistoryAlert();
			// } else {
			// makeToast("Refreshing...");
			// }

		}

	}

	// the save action
	class SaveAction implements Action {

		public int getDrawable() {
			return R.drawable.ic_action_search;
		}

		public void performAction(View view) {
			makeToast("Saving...");
		}

	}

	// the settings action
	class SettingsAction implements Action {

		public int getDrawable() {
			return R.drawable.ic_action_settings;
		}

		public void performAction(View view) {
			if (currentActivity.getClass().getSimpleName()
					.equals("SettingsActivity")) {
			} else {
				Intent settings = new Intent(currentActivity,
						SettingsActivity.class);
				LoginDialog(settings, "Settings");
			}
		}

	}



	// the about us action
	class AboutAction implements Action {

		public int getDrawable() {
			return R.drawable.ic_action_about;
		}

		public void performAction(View view) {
			Intent about = new Intent(getApplicationContext(),
					AboutActivity.class);
			if (currentActivity.getClass().getSimpleName()
					.equals("AboutActivity")) {
			} else {
				if (currentActivity.getClass().getSimpleName()
						.equals("SettingsActivity")) {
					finish();
				}
				startActivity(about);
			}

		}

	}

	public static void makeToast(String message) {
		// with jam obviously
		Toast.makeText(currentActivity, message, Toast.LENGTH_SHORT).show();
	}

	public static boolean isEmailFormatValid(String input) {
		String expression = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,6}|[0-9]{1,3})$";
		// String expression =
		// "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
		CharSequence inputStr = input.toLowerCase();
		Pattern pattern = Pattern.compile(expression);
		Matcher matcher = pattern.matcher(inputStr);

		if (matcher.matches()) {
			return true;
		} else {
			makeToast("The email address you entered is not in a valid format.");
			return false;
		}
	}
	
	public static boolean isPasswordFormatValid(int input) {
		if (input >= 6){
			return true;
		} else {
			makeToast("You must enter a password that is at least 6 digits long.");
			return false;
		}
			
	}

}